//
//  KAOTPVC.swift
//  kano
//
//  Created by Sophia on 2024/8/20.
//


import UIKit
import SnapKit
import RxSwift
import RxCocoa

class KAOTPVC: KABaseVC {
    var pwd: String = ""
    var codeToken: String = ""
    var operationType: KAOperation = .Register
    private var verifyToken: String = ""
    
    private let disposeBag = DisposeBag()
    private let titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: kscale(24), weight: .bold)
        titleLabel.textColor = .black
        titleLabel.text = "Enter OTP"
        titleLabel.x = kscale(20)
        titleLabel.y = kscale(40) + UIDevice.ka_fullNavHeight
        titleLabel.width = var_screenWidth-kscale(40)
        titleLabel.height = kscale(32)
        return titleLabel
    }()
    private let subTitleLabel: UILabel = {
        let subTitleLabel = UILabel()
        subTitleLabel.textAlignment = .center
        subTitleLabel.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        subTitleLabel.textColor = .color8A8891
        subTitleLabel.x = kscale(20)
        subTitleLabel.y = kscale(70) + UIDevice.ka_fullNavHeight
        subTitleLabel.width = var_screenWidth-kscale(40)
        subTitleLabel.height = kscale(32)
//        let holderText = "Please use +"
        let phoneNumber = KAUserManager.shared.user.notificationMessage.maskedNumber
        let phoneStr = "+234 \(phoneNumber)"
        let allText = "Please use " + phoneStr + " to get the code"
        let attributedString = NSMutableAttributedString(string: allText)
        let holderTextRange = allText.nsRange(of: phoneStr)
        attributedString.addAttributes([
            .font: UIFont.systemFont(ofSize: kscale(11)),
            .foregroundColor: UIColor.themeColor
        ], range: holderTextRange)
        subTitleLabel.attributedText = attributedString
        return subTitleLabel
    }()
    private lazy var msgView: KAAuthView = {
        msgView = KAAuthView(count: 6, margin: kscale(12.5), borderColor: .color7E7EEC, backgroundColor: .color7E7EEC, handler: { code in
            if code.count == 6 {
//                if self.operationType == .Register {
//                    self.ka_verifyCode()
//                } else if self.operationType == .OldPhoneLogin {
//                    self.loginRequest()
//                }
                self.ka_verifyCode()
            }
        })
        msgView.editDidEndHandle = { cell, tfInfo in
            tfInfo.geographicalLongitude = "identity_document_verification"
            tfInfo.paginationId = "NewLogin_Process"
            KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
        }
        return msgView
    }()
    private lazy var resendBtn: UIButton = {
        let resendBtn = UIButton()
        resendBtn.backgroundColor = .colorf2f2f5
        resendBtn.setTitle("Get Verification Code", for: .normal)
        resendBtn.setTitleColor(.themeColor, for: .normal)
        resendBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        resendBtn.addTarget(self, action: #selector(resendBtnClick), for: .touchUpInside)
        return resendBtn
    }()
    @objc func resendBtnClick() {
        if resendBtn.titleLabel?.text == "Get Verification Code" {
            let btnInfo = KABtnInfo(eleId: "creditProcess_status", pageId: "NewLogin_Process", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        }
        if resendBtn.titleLabel?.text == "Resend" {
            var eleId = currentCodeType == "0" ? "loanStay_process" : "creditCard_add"
            let btnInfo = KABtnInfo(eleId: eleId, pageId: "NewLogin_Process", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        }
        ka_sendCode()
    }
    var firstVoiceClick: Bool = true
    @objc func voiceCodeBtnClick() {
        currentCodeType = currentCodeType == "0" ? "1" : "0"
        if resendBtn.titleLabel?.text == "Resend" {
            var eleId = currentCodeType == "0" ? "loanStay_process" : (firstVoiceClick ? "exitFlow_complete" : "creditCard_add")
            let btnInfo = KABtnInfo(eleId: eleId, pageId: "NewLogin_Process", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        }
        firstVoiceClick = false
        ka_sendCode()
    }
    private lazy var voiceCodeBtn: UIButton = {
        let voiceCodeBtn = UIButton()
        voiceCodeBtn.backgroundColor = .colorf2f2f5
        voiceCodeBtn.setTitle("Voice code", for: .normal)
        voiceCodeBtn.setTitleColor(.themeColor, for: .normal)
        voiceCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        voiceCodeBtn.addTarget(self, action: #selector(voiceCodeBtnClick), for: .touchUpInside)
        voiceCodeBtn.isHidden = true
        return voiceCodeBtn
    }()
    
    lazy var var_pictureView: KAPictureVerifyView = {
        let var_pictureView = KAPictureVerifyView { [self] code, captcheId in
            captchaId = captcheId
            captchaCode = code
//            ka_sendCode()
//            if self.operationType == .Register {
//                self.ka_verifyCode()
//            } else if self.operationType == .OldPhoneLogin {
//                self.loginRequest()
//            }
            self.ka_verifyCode()
        }
        return var_pictureView
    }()
    
    private var count: Int = 60
    private var task: String?
    private var currentCodeType: String = "0"
    private var captchaCode: String = ""
    private var captchaId: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        setConstraints()
        resendBtnClick()
        let data = KAPageInfo(eleId: "login_security_audit", path: "\(KAOTPVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        guard task != nil else { return }
        KATimer.cancelTask(task!)
    }
    
    private func setUI() {
        view.backgroundColor = .colorf2f2f5
        ka_showCustomerNavBar(type: .normal)
        var_navBar.updateUI(alpha: 0)
        
        view.addSubview(titleLabel)
        view.addSubview(subTitleLabel)
        view.addSubview(msgView)
        view.addSubview(resendBtn)
        view.addSubview(voiceCodeBtn)
        view.becomeFirstResponder()
    }
    
    private func setConstraints() {
  
        msgView.snp.makeConstraints { make in
            make.top.equalTo(subTitleLabel.snp.bottom).offset(kscale(41))
            make.left.equalTo(kscale(24))
            make.right.equalTo(kscale(-24))
            let width = (var_screenWidth - kscale(48) - kscale(60)) / 6
            make.height.equalTo(width)
        }
        
        resendBtn.snp.makeConstraints { make in
            make.top.equalTo(msgView.snp.bottom).offset(kscale(10))
            make.right.equalTo((kscale(-24)))
        }
        voiceCodeBtn.snp.makeConstraints { make in
            make.top.equalTo(msgView.snp.bottom).offset(kscale(10))
            make.left.equalTo(kscale(24))
        }
    }
    
    private func ka_sendCode() {
        //注册发送验证码
        KAAFTool.logEvent(event: "SKP_sendverification_code")
        
        NetService.ka_sentCode(withType: currentCodeType, codeToken: codeToken, operationType: operationType, captchaCode: captchaCode) { [self] isSuccess, message, response in
//            self.captchaId = ""
//            self.captchaCode = ""
            if isSuccess {
                var eleId = currentCodeType == "0" ? "processCard_info" : "loanExit_status"
                let toastInfo = KAToastInfo(eleId: eleId, pageId: "NewLogin_Process", path: "\(KAOTPVC.self)")
                KAReport.ka_reportWith(type: .toast, data: toastInfo.kj.JSONObject())
                
                var toast = currentCodeType == "0" ? "\(var_smsToast) \(KAUserManager.shared.user.notificationMessage)." : var_voiceToast
                self.view.makeToast(toast)
                if response?.voucherQuantity != nil {
                    self.verifyToken = (response?.voucherQuantity!.authenticationToken)!
                }
                startTimer()
                self.var_pictureView.dismiss()
            } else {
                guard let status = response?.operationalStatus else { return }
                if ka_showPictureView(status) {
                    self.var_pictureView.show()
                    self.var_pictureView.makeToast(message)
                    return
                }
                self.view.makeToast(message)
                self.var_pictureView.dismiss()
            }
        }
    }
    
    private func ka_verifyCode() {
        let mobile = KAUserManager.shared.user.notificationMessage
        let paramDic: [String: Any] = [
            "notificationMessage": mobile,
            "validityStartTime": msgView.code,
            "authorizationco": verifyToken,
            "authenticationToken": codeToken,
            "processActionType": operationType.rawValue,
            "uniqueUserIdentifier": UIDevice.ka_UUID,
            "repaymentSum": 1,
            "renewalRepaidCapital": captchaId,
            "securityCode": captchaCode,
            "imageCodeVerification": captchaCode.isEmpty ? false : true,
        ]
        view.showLoading()
        loginProvider.request(.checkSmsCode(paramDic)) { [self] result in
            view.hideLoading()
            self.captchaId = ""
            self.captchaCode = ""
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else {
                                view.makeToast("Verification failure"); return
                            }
                            if content.operationalStatus == 1 {
                                if self.operationType == .OldPhoneLogin {
                                    let newUser = KAUserManager.shared.user
                                    KAUserManager.shared.userLogin(with: newUser.notificationMessage)
                                } else {
                                    self.var_pictureView.dismiss()
                                    //accountkit注册成功跳转设置密码
                                    KAAFTool.logEvent(event: "SKP_Jumptoset_password")
                                    
                                    let vc = KAPwdSetVC()
                                    vc.codeToken = verifyToken
                                    vc.verifyToken = msgView.code
                                    navigationController?.pushViewController(vc, animated: true)
                                }
                                return
                            }
                            view.makeToast("Verification failure")
                        } else {
                            guard let status = response?.operationalStatus else { return }
                            if ka_showPictureView(status) {
                                self.var_pictureView.show()
                                self.var_pictureView.makeToast(message)
                                return
                            }
                            self.view.makeToast(message)
                            self.var_pictureView.dismiss()
                            self.msgView.clearContent()
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                    self.msgView.clearContent()
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
//    private func loginRequest() {
//        NetService.ka_loginWith(mobile: KAUserManager.shared.user.notificationMessage, password: pwd, codeToken: codeToken, operationType: operationType, verifyCode: msgView.code, verifyToken: verifyToken, captchaCode: captchaCode, captchaId: captchaId, secondLogin: 0) {[self] isSuccess, message, response in
//            if (!isSuccess) {
//                guard let status = response?.operationalStatus else { return }
//                if  ka_showPictureView(status) {
//                    self.var_pictureView.show()
//                    self.var_pictureView.makeToast(message)
//                    return
//                }
//                self.view.makeToast(message)
//                self.var_pictureView.dismiss()
//                self.msgView.clearContent()
//            }
//        }
//    }
    
    private func startTimer() {
        count = 60
        task = KATimer.execTask(self, selector: #selector(countdown), start: 0.0, interval: 1.0, repeats: true, async: false)
    }
    
    @objc private func countdown() {
        let button: UIButton = resendBtn
        
        if count > 0 {
            count -= 1
            button.isUserInteractionEnabled = false
            button.setTitleColor(.color8A8891, for: .normal)
            voiceCodeBtn.isHidden = true
            let string = "(" + "\(count)" + "s)"
            button.setTitle(string, for: .normal)
        } else {
            KATimer.cancelTask(task!)
            button.isUserInteractionEnabled = true
            button.setTitleColor(.themeColor, for: .normal)
            voiceCodeBtn.isHidden = false
            button.setTitle("Resend", for: .normal)
            var title = currentCodeType == "0" ? "Voice code" : "SMS code"
            voiceCodeBtn.setTitle(title, for: .normal)
        }
    }
}
